<?php

namespace app\api\controller\user;

use app\common\controller\Api;
use app\common\model\User as UserModel;
use app\common\exception\UploadException;
use app\api\common\Program;
use app\common\library\Upload;
use think\Db;
use think\Config;
use app\common\controller\Pic;


class User extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 用户信息
     * @ApiMethod (POST)
     * @path api/user/user/info
     */
    public function info()
    {
        $user_id = $this->auth->id;
        $storeId = $this->auth->store_id;
        $store = db('store')->field('store_name,avatar')->where('id',$storeId)->find();

        $waitPayNum = db('order')->where(['user_id'=>$user_id,'store_id'=>$storeId,'order_status'=>0])->where('order_type','in',[1,2])->count();
        $waitSend = db('order')->where(['user_id'=>$user_id,'store_id'=>$storeId,'order_status'=>1])->where('order_type','in',[1,2])->count();
        $waitZiti = db('order')->where(['user_id'=>$user_id,'store_id'=>$storeId,'order_status'=>2])->where('order_type','in',[1,2])->count();
        $waitTake = db('order')->where(['user_id'=>$user_id,'store_id'=>$storeId,'order_status'=>3])->where('order_type','in',[1,2])->count();
        $info = UserModel::user_info($user_id);

        $info['waitPayNum'] = $waitPayNum;
        $info['waitSend'] = $waitSend;
        $info['waitZiti'] = $waitZiti;
        $info['waitTake'] = $waitTake;
        $info['store'] = $store;
        $this->success('请求成功',$info);
    }

    /**
     * 修改用户信息
     * @ApiMethod (POST)
     * @param string $username 用户昵称
     * @param string $image 用户头像
     * @path api/user/user/profile
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $image = $this->request->post('image', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = UserModel::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('用户昵称已存在'));
            }
            if($user->open_id){
                $res = Program::TextRecognition($username,$user->open_id);
                if($res['code'] == 200 && $res['label'] != 100){
                    $this->error($res['data']);
                }elseif ($res['code'] == 201) {
                    $this->error($res['data']);
                }
            }
            $user->username = $username;
        }
        if($image){
            if($user->open_id){
                $res = Program::VideoRecognition(parse_url($image)["path"],2,$user->open_id);
                if($res['code'] == 200 && $res['label'] != 100){
                    $this->error($res['data']);
                }elseif ($res['code'] == 201) {
                    $this->error($res['data']);
                }
            }
            $user->image = parse_url($image)["path"];
        }
        $user->save();
        $this->success("修改成功");
    }

    /**
     * 意见反馈
     * @path api/user/user/onlineMessage
     */
    public function onlineMessage()
    {
        $user_id = $this->auth->id;
        $content = $this->request->post('content');
        if (!$content){
            $this->error(__('反馈内容不能为空'));
        }
        $data = [
            "user_id"=>$user_id,
            "content"=>$content,
            "add_time"=>time(),
        ];
        $res = Db::name("advice")->insert($data);
        if ($res){
            $this->success("反馈成功");
        }else{
            $this->error("反馈失败");
        }
    }

    /**
     * 搜索历史
     * @ApiMethod (POST)
     * @path api/user/user/searchHistory
     */
    public function searchHistory()
    {
        $user_id = $this->auth->id;
        $where = "user_id = {$user_id}";
        $field = "id,name";
        $order = "add_time DESC";
        $list = Db::name("search_history")->where($where)->field($field)->order($order)->select();
        $this->success("请求成功",$list);
    }

    /**
     * 删除搜索历史
     * @ApiMethod (POST)
     * @path api/user/user/delSearchHistory
     */
    public function delSearchHistory()
    {
        $user_id = $this->auth->id;
        $search_id = $this->request->post('search_id');
        $where = "user_id = {$user_id}";
        if($search_id){
            $where.= " AND id = {$search_id}";
        }
        Db::name("search_history")->where($where)->delete();
        $this->success("删除成功");
    }

    /**
     * 上传文件
     * @ApiMethod (POST)
     * @param $file
     * @path api/user/user/upload
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'full_url' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('filePath');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'full_url' => cdnurl($attachment->url, true)]);
        }
    }

    /**
     * 我的邀请二维码
     * @ApiMethod (POST)
     * @path api/user/user/myErcode
     */
    public function myErcode()
    {
//        $picServices = new Pic();
//        $imgg = $picServices->radius_img('D:\phpstudy_pro\WWW\web.jianjimei.test\jianji\public\avatar.png',15);
//
//        $res = imagejpeg($imgg,'D:/phpstudy_pro/WWW/web.jianjimei.test/jianji/public/2222222.jpg',100);
//        var_dump($res);die;
//
//        var_dump($myQrcode1);die;
        $rootPath = $_SERVER['DOCUMENT_ROOT'];
        $user = $this->auth->getUser()->toArray();
        if (empty($user['store_id'])) {
            $this->error("请先绑定空间后再分享");
        }
        $imageAva = db('user')->where('id',$user['id'])->value('image');
        $myQrcode = db('user')->where('id',$user['id'])->value('xcx_qrcode');
        //if (empty($myQrcode)) {
            $wxJssdk = new Program();
            $accessToken = $wxJssdk->getAccessToken();
            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$accessToken['data']['access_token'];
            // 生成带参数的二维码
            // $postData = [
            //     'scene' => $user['id'],
            //     'env_version' => 'trial',
            //     'page' => 'pages/Home/Home',
            //     'check_path' => false
            // ];
            $postData = [
                'scene' => $user['id'],
                'env_version' => 'release',
                'page' => 'pages/Home/Home',
                'check_path' => true
            ];

            $result = curlPost($url,json_encode($postData));
            // 保存二维码图片
            $imagePath = $rootPath."/xcx_user_qrcode/".$user['id'].".png"; // 保存二维码的路径
            file_put_contents($imagePath, $result);

            $myQrcode = $rootPath."/xcx_user_qrcode/".$user['id'].".png";
            if (empty($imageAva)) {
                $user['image'] = $rootPath.'avatar.png';
            }
            $avatar = $rootPath.$imageAva;

            $picServices = new Pic();
            $myQrcode1 = $picServices->poster($myQrcode,$avatar,$rootPath,$user['username']);
            db('user')->where('id',$user['id'])->update(['xcx_qrcode'=>$myQrcode1]);
            $backData = [
                'image'=>$myQrcode1
            ];
        $backData = addWebSiteUrl($backData,['image']);
        //}
        $this->success("操作成功",$backData);
    }

}

